package com.itheima.demo;

import cn.hutool.core.util.StrUtil;
import com.itheima.domain.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author: Sch
 * @Date: 2025/07/17 16:16
 * @Description:
 */
//@Component
public class AuthorizedInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("AuthorizedInterceptor preHandler");

        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        try{
            Claims claims = JwtUtils.parseJWT(token);//解析Jwt令牌
            Object id = claims.get("id");
            return  true;
        }catch (Exception e){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }

}
